using System;
using System.IO;
using System.Linq;
using KTOP.Core.Extensions;

namespace KTOP.Core.Formatters
{
    public class TextTableFormatter
    {
        [Flags]
        public enum Borders
        {
            None = 0, 
            ColsOnly = 1,
            RowsOnly = 2,
            ColsAndRows = 3
        }

        public void Format(TextWriter tw, string[][] table, Borders borders)
        {
            var rows = table.Length;
            var cols = table.Max(r => r.Length);

            var colSizes = new int[cols];

            for (var row = 0; row < rows; row++)
                for (var col = 0; col < cols; col++)
                {
                    if (col >= table[row].Length) break;

                    var colSize = table[row][col].Length;
                    if (colSize > colSizes[col]) colSizes[col] = colSize;
                }

            var rowJoinChar = borders.HasFlag(Borders.ColsOnly) ? "|" : " ";
            var colJoinStr = new string('-', colSizes.Sum() + colSizes.Length - 1);

            if (borders.HasFlag(Borders.RowsOnly)) tw.WriteLine(colJoinStr);
            foreach (var row in table
                .Select(row => string.Join(rowJoinChar, row.Select((cell, col) => cell.AppendChars(colSizes[col], ' ')))))
            {
                tw.WriteLine(row);
                if (borders.HasFlag(Borders.RowsOnly)) tw.WriteLine(colJoinStr);
            }
        }
    }
}